package units

import (
	"sieve_admin_server_userpass/pkg/cache"
	"sieve_admin_server_userpass/pkg/im3/db"
	"sieve_admin_server_userpass/pkg/log"
)

var (
	c    = cache.PeriodLoad(db.LoaderPeriod, loadList)
	dbok = false
)

func init() {
	db.OnConnected(func() {
		dbok = true
		c.Load()
	})
}

type Unit struct {
	Id    int
	Name  string
	Pwd   string
	Order int
}

func loadList() (list []*Unit) {
	list = []*Unit{}
	if !dbok {
		return
	}
	rows, err := db.Mysql().Query("SELECT `id`,`Name`,`Pwd`,`Order` FROM `Unit` WHERE `Order`>0 ORDER BY `Order` DESC,`id`")
	if err != nil {
		log.Err(err)
		return
	}
	defer rows.Close()
	for rows.Next() {
		u := &Unit{}
		if err := rows.Scan(
			&u.Id,
			&u.Name,
			&u.Pwd,
			&u.Order,
		); err != nil {
			log.Err(err)
			return
		}
		list = append(list, u)
	}
	return
}

func Reload() {
	c.Load()
}

func GetAll() []*Unit {
	return c.Get()
}

func Get(id int) *Unit {
	for _, u := range c.Get() {
		if u.Id == id {
			return u
		}
	}
	return nil
}
